import {defineStore} from "pinia";
import {computed, onMounted, ref, watch} from "vue";
import {StorageSerializers, useStorage} from "@vueuse/core";
import {reqInstance} from "@/utils/request/index.js";
import {message} from "ant-design-vue";

export const useCompanyStore = defineStore("companyStore", () => {
    const companyList = ref([])
    const nowComID = ref(0)
    const nowComName = computed(()=>{
        const t = companyList.value.find(t=>t.id === nowComID.value)
        return t?t.com_name:"暂无企业"
    })


    useStorage("now-com-id",nowComID)

    const getCompany = async () => {
        try {
            const res = await reqInstance({
                url: "/company",
                method: "get",
            })
            companyList.value = res?.data ?? []
            if ( companyList.value.length > 0 && nowComID.value === 0) {
                nowComID.value = companyList.value[0].id
            }
        } catch (e) {

        }
    }

    // if (nowComID.value === 0 ) {
    //     getCompany()
    // }
    onMounted(async ()=>{
        if (nowComID.value === 0 ) {
            await getCompany()
        }
    })

    return {getCompany,companyList,nowComID,nowComName}
})